package com.efounder.view;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


import com.efounder.core.VoicePlayer;
import com.efounder.core.VoiceRecorderAbstract;
import com.efounder.core.VoiceRecorder_endWithMP3;
import com.efounder.mobilecomps.R;

import java.io.File;


/***
 * @author meijun
 *
 * use it
 * eg:
 *    BottomDialog bottomDialog = BottomDialog.newInstance();
 *      bottomDialog.show(getSupportFragmentManager(), new BottomDialog.PathInterface() {
 *       @Override
 *      public void recordFinish(String recordFilePath) {
 *       Toast.makeText(MainActivity.this, recordFilePath, Toast.LENGTH_SHORT).show();
 *   }
 *      });
 *
 *
 *
 *
 */
public class BottomDialog extends DialogFragment implements View.OnClickListener {

    private ImageView imageButton;
    private View view;
    private TextView textview;
    private Button cancle;
    private Button confirm;
    private VoiceRecorderAbstract voiceRecorder;
    private String filePath;
    private VoicePlayer voicePlayer;
    private PlayView play2;
    private TextView textright;
    private TextView textleft;

    public static BottomDialog newInstance() {

        Bundle args = new Bundle();

        BottomDialog fragment = new BottomDialog();
        fragment.setArguments(args);
        return fragment;
    }

    int count = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                StringBuilder builder = new StringBuilder();
                int temp = count;

                int minu = temp / 60;
                builder.append(minu);
                builder.append(":");
                temp = temp % 60;
                if (temp < 10) {
                    builder.append(0);
                    builder.append(temp);
                } else {
                    builder.append(temp);
                }


                if (isRecording) {
                    count++;
                    textview.setText(builder.toString());
                    handler.sendEmptyMessageDelayed(0, 1000);
                    isPlaying = false;
                }

                if (isPlaying) {
                    count++;
                    textview.setText(builder.toString());
                    isRecording = false;
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.gravity = Gravity.BOTTOM;
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        //params.dimAmount = 0.0f;
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    Handler recordHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };

    private static final String TAG = "BottomDialog";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        view = inflater.inflate(R.layout.dialog_bottom, container, false);
        textleft = (TextView) view.findViewById(R.id.left);
        textright = (TextView) view.findViewById(R.id.right);
        imageButton = (ImageView) view.findViewById(R.id.button);
        textview = (TextView) view.findViewById(R.id.ddddd);
        cancle = (Button) view.findViewById(R.id.cancle);
        cancle.setOnClickListener(this);
        confirm = (Button) view.findViewById(R.id.confirm);
        confirm.setOnClickListener(this);
        imageButton.setOnClickListener(this);
        play2 = (PlayView) view.findViewById(R.id.play2);
        play2.setOnClickListener(this);
        slideToUp(view);

        voiceRecorder = new VoiceRecorder_endWithMP3(recordHandler, this.getContext());
        voicePlayer = new VoicePlayer(this.getContext(), new Handler());
        return view;
    }

    public static void slideToUp(View view) {
        Animation slide = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.0f);

        slide.setDuration(400);
        slide.setFillAfter(true);
        slide.setFillEnabled(true);
        view.startAnimation(slide);
    }

    private boolean isRecording = false;
    private boolean isPlaying = false;

    public void show(FragmentManager transaction, PathInterface pathInterface) {
        this.pathInterface = pathInterface;
        super.show(transaction, "tag");
    }

    PathInterface pathInterface;


    /**
     * 0代表默认状态
     * 1代表录音状态
     * 2代表待播放状态
     * 3代表播放状态
     */
    private int state = 0;

    @Override
    public void onClick(final View v) {


        if (v.getId() == R.id.play2 || v.getId() == R.id.button) {

            if (state == 0) {
                //进入录音状态
                isRecording = true;
                textview.setText("准备中..");
                Drawable drawable = getContext().getResources().getDrawable(R.drawable.select_blue);
                v.setBackgroundDrawable(drawable);
                isPlaying = false;
                state = 1;
                handler.sendEmptyMessageDelayed(0, 1000);
                filePath = voiceRecorder.startRecording();

            } else if (state == 1) {
                //进入待播放状态

                v.setBackgroundResource(R.drawable.select_gree);
                voiceRecorder.stopRecoding();
                isRecording = false;
                isPlaying = false;
                cancle.setVisibility(View.VISIBLE);
                confirm.setVisibility(View.VISIBLE);
                //待播放状态;
                state = 2;

            } else if (state == 2) {
                //进入播放状态
                //最上面显示分钟数

                isPlaying = true;
                isRecording = false;
                imageButton.setVisibility(View.INVISIBLE);
                play2.setVisibility(View.VISIBLE);
                play2.start(count);
                count = 0;
                textview.setText("播放中...");
                handler.sendEmptyMessageDelayed(0, 0);

                voicePlayer.playVoice(filePath);
                state = 3;
                play2.setonStateChangeListener(new VoicePlayer.OnstateChangeListener() {
                    @Override
                    public void playComplete() {
                        enterWaitingPlayState(v);
                        isRecording = false;
                        isPlaying = false;
                    }
                });

            } else if (state == 3) {
                isPlaying = false;
                isRecording = false;
                //进入待播放状态
                enterWaitingPlayState(v);
            }


        }

        //确认按钮

        if (v.getId() == R.id.confirm) {
            //确定

            this.dismiss();

            giveVoicePath();
        }
        //取消按钮

        if (v.getId() == R.id.cancle) {
            if (isPlaying) {
                voicePlayer.stopPlayVoice();
                isPlaying = false;
            }
            enterPrepareState();
            //重录删除之前的
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    private void giveVoicePath() {
        pathInterface.recordFinish(filePath);

    }

    private void enterPrepareState() {
        state = 0;
        count = 0;
        textview.setText("点击录音");
        cancle.setVisibility(View.INVISIBLE);
        confirm.setVisibility(View.INVISIBLE);
        imageButton.setVisibility(View.VISIBLE);
        play2.setVisibility(View.INVISIBLE);
        imageButton.setBackgroundResource(R.drawable.select_red);
    }

    private void enterWaitingPlayState(View v) {
        imageButton.setVisibility(View.VISIBLE);
        play2.setVisibility(View.INVISIBLE);
        v.setBackgroundResource(R.drawable.select_gree);
        voicePlayer.stopPlayVoice();
        state = 2;
    }

    public interface PathInterface {
        void recordFinish(String recordFilePath);
    }
}


